<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        width: 375px;
        height: 667px;
        border: 1px solid #000;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <div id="box"></div>
      <input type="text" />
      <button>发送</button>
    </div>

    <script>
      const name = prompt("请输入名字");
      const id = new Date().getTime();

      const box = document.querySelector("#box");
      const ipt = document.querySelector("input");
      const btn = document.querySelector("button");

      // 连接websocket服务
      // 协议是ws或者wss
      var ws = new WebSocket("ws://192.168.5.99:8080");

      // 连接成功的回调
      ws.onopen = function (evt) {
        console.log("Connection open ...");
        // 前端向后端发送
        // ws.send("Hello WebSockets!");
      };

      // 前端接受到后端的信息
      ws.onmessage = function (evt) {
        // console.log("Received Message: " + evt.data);
        // 前端主动断开连接
        // ws.close();

        const obj = JSON.parse(evt.data);

        if (obj.id === id) {
          box.innerHTML += `<p style="text-align: right">${obj.name}说：${obj.value}</p>`;
        } else {
          box.innerHTML += `<p style="text-align: left">${obj.name}说：${obj.value}</p>`;
        }
      };

      // 前端断开连接的回调
      ws.onclose = function (evt) {
        console.log("Connection closed.");
      };

      btn.onclick = () => {
        // console.log(ipt.value);
        // ws.send(name + "说：" + ipt.value);
        ws.send(
          JSON.stringify({
            name,
            value: ipt.value,
            id,
          })
        );
        ipt.value = "";
      };
    </script>
  </body>
</html>
